import axios from 'axios'
import qs from 'qs'

const baseURL = ''

axios.defaults.timeout = 10000;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.baseURL = baseURL;

xios.interceptors.request.use((config) => {
  if (config.method === 'post') {
    config.data = qs.stringify(config.data);
  }
  return config;
}, (error) => {
  Message({
    type: 'error',
    message: "错误的传参"
  })
  return Promise.reject(error);
});

axios.interceptors.response.use((res) => {
  if (res.data.retcode == 0) {
    return res
  } else if (res.data.retcode == '403') {
    location.href = '#/login';
  } else {
    Message({
      type: 'error',
      message: res.data.retmsg
    })
    // return Promise.reject(res);
    return res
  }
}, (error) => {
  console.log(error)
  Message({
    type: 'error',
    message: "网络异常"
  })
  return Promise.reject(error);
})

//返回一个Promise(发送post请求)
export function fetchPost(url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err);
      })
      .catch((error) => {
        reject(error)
      })
  })
}

// 返回一个Promise(发送get请求)
export function fetchGet(url, param) {
  return new Promise((resolve, reject) => {
    axios.get(url, {params: param})
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
